package org.example;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class AES {

    public static void main(String[] args) {
        try {
            // 生成AES密钥
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(256); // 使用256位密钥长度
            SecretKey secretKey = keyGenerator.generateKey();

            // 将密钥转换为SecretKeySpec
            byte[] keyBytes = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

            // 要加密的原始字符串
            String originalString = "11209628e333df9dc335b9de70c785fcd7b24f01df4946af7f7d0581069855bb";

            // 加密
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encryptedBytes = cipher.doFinal(originalString.getBytes());
            String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);

            // 打印加密后的字符串
            System.out.println("Encrypted: " + encryptedString);

            // 解密
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
            String decryptedString = new String(decryptedBytes);

            // 打印解密后的字符串
            System.out.println("Decrypted: " + decryptedString);

        } catch (NoSuchAlgorithmException | javax.crypto.NoSuchPaddingException |
                 java.security.InvalidKeyException |
                 javax.crypto.IllegalBlockSizeException | javax.crypto.BadPaddingException e) {
            e.printStackTrace();
        }
    }

}
